package com.mg.admin.realm;

import com.mg.admin.bean.admin.Result;
import com.mg.admin.bean.admin.UserVO;
import com.mg.admin.constants.Constants;
import com.mg.admin.service.admin.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class UserRealm extends AuthorizingRealm {

	@Autowired
	private UserService userService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = (String)principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		Result<UserVO> result = userService.login(username,null);
		UserVO userVO = result.getData();
		authorizationInfo.setRoles(userVO.getRoles());
		Set<String> permissions = userVO.getPermissions();
		if (username.equals("admin")){
			permissions.add("*:*");
		}
		authorizationInfo.setStringPermissions(permissions);
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

		String userno = (String) authenticationToken.getPrincipal();

		String password = new String((char[]) authenticationToken.getCredentials());

		Result<UserVO> result =  userService.login(userno, password);

		if (result.isSuccess()){

			UserVO userVO = result.getData();

			Session session = SecurityUtils.getSubject().getSession();

			session.setAttribute(Constants.SESSION_KEY,userVO);

			return new SimpleAuthenticationInfo(userVO.getUsername(), userVO.getPassword() ,getName());
		}
		return null;
	}

}
